import { ref,reactive,unref,onMounted } from 'vue';
import { post } from "@/utils/http";
import request from '@/utils/axios' 

// 接收两个参数，一个是请求地址，一个是查询（搜索）参数
export function useHttp(url, initialParams) {
    // 初始值
    const loading = ref(false);// 加载状态
    const pageInfo =reactive({
        page: 1,
        pageSize:10
    })
    const dataList = ref([]);
    const totals = ref(0);

    // 加载数据函数
    const loadData = async () => {
        loading.value = true;
        try {
            let response =await post(url,{...pageInfo,...unref(initialParams)})
            //返回数据列表与总数        
            dataList.value = response.data.list;
            totals.value = response.data.total;
        } catch (error) {
            console.error(error);
        }finally{
            loading.value = false;
        }

    };
    onMounted(() => {
        loadData();
    });
    // 分页相关事件处理函数
    const handleSizeChange = (size) => {
        console.log("handleSizeChange");
        pageInfo.pageSize = size;
        loadData();
    };

    const handleCurrentChange = (page) => {
        console.log("handleCurrentChange");
        pageInfo.page = page;
        loadData();
    };

    const resetPagination = () => {
        pageInfo.page = 1;
        pageInfo.pageSize = 10; 
        loadData();
    };

    return {
        dataList,
        loading,
        loadData,
        totals,
        pageInfo,
        handleSizeChange,
        handleCurrentChange,
        resetPagination,
    };
}